import 'dart:convert';

import 'package:get/get.dart';
import 'package:tin_flutter/app/app_data.dart';
import 'package:tin_flutter/app/global.dart';
import 'package:tin_flutter/app/network/http_service.dart';
import 'package:tin_flutter/app/tools/logger.dart';
import 'package:tin_flutter/ui/activity/login/login_state.dart';
import 'package:tin_flutter/ui/bean/request/login_request_entity.dart';

import '../../../app/routes.dart';
import '../../../app/tools/aes_util.dart';

class LoginLogic extends GetxController {
  final state = LoginState();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  /// 登录
  /// * [username] 用户名
  /// * [password] 密码
  /// * [code] 验证码
  void login(String username, String password, String code) async {
    if (username.isEmpty) {
      showToast('请输入用户名', type: ToastType.error);
      return;
    }
    if (password.isEmpty) {
      showToast('请输入密码', type: ToastType.error);
      return;
    }
    if (code.isEmpty) {
      showToast('请输入验证码', type: ToastType.error);
      return;
    }
    LoginRequestEntity request = LoginRequestEntity();
    request.username = username;
    request.password = password;
    request.code = code;
    var encryptedData = AesUtil().encrypt(jsonEncode(request.toJson()));
    HttpService.login(encryptedData).then((value) {
      logger('登录成功, $value');
      AppData.setUsername(username);
      AppData.setPassword(password);
      AppData.setUserType(value.type);
      AppData.setUserTypeId(value.id);
      AppData.setUserTypeName(value.bindName);
      showToast('登录成功');
      // 延时1s后跳转主页面
      Future.delayed(const Duration(seconds: 1), () {
        Get.offAllNamed(Routes.main);
      });
    }).onError((error, StackTrace) {
      logger('登录失败, ${error}');
    });
  }
}
